import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/base/base_app_state_page.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/generated/json/base/json_convert_content.dart';
import 'package:library_base/entities/in_order_page_goods_details_entity.dart';
import 'package:library_base/entities/location_entity.dart';
import 'package:library_base/entities/reason_entity.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/network/http_util.dart';
import 'package:library_base/network/transform/fb_parse_transform.dart';
import 'package:library_base/res/decoration.dart';
import 'package:library_base/res/dividing_line.dart';
import 'package:library_base/res/edge.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/picker/time_picker.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/widget_generate_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/utils/get_util.dart';
import 'package:library_base/widget/image/local_image.dart';

class CreateWmsDialog extends StatefulWidget {
  const CreateWmsDialog({
    Key? key,
  }) : super(key: key);

  @override
  State<CreateWmsDialog> createState() => _CreateWmsDialogState();
}

class _CreateWmsDialogState extends State<CreateWmsDialog> {

  var loginEnabled = false;

  late String id;

  late String goodsCode;

  late int stockInCount;

  late double stockInWeight;

  String? locationId;

  String? locationName;

  late int position;

  late Function(
      int position, List<InOrderPageGoodsDetailsEntity> listDetails,String locationId,String locationName,String? differenceReason) updatePosition;

  late List<InOrderPageGoodsDetailsEntity> list;

  ///商品条码
  LocationEntity? goodsLocation;

  ReasonEntity? reason;

  late String serviceUnit;

  @override
  void initState() {
    super.initState();
    goodsLocation = Get.arguments['goodsLocation'];
    reason = Get.arguments['reason'];
    id = Get.arguments['id'];
    goodsCode = Get.arguments['goodsCode'];
    locationId = Get.arguments['locationId'];
    locationName = Get.arguments['locationName'];
    updatePosition = Get.arguments['updatePosition'];
    list = Get.arguments['goodsDetails'];
    stockInCount = Get.arguments['stockInCount'];
    serviceUnit = Get.arguments['serviceUnit'];
    stockInWeight = Get.arguments['stockInWeight'];
    position = Get.arguments['position'];
    if(locationName!=null && locationId!=null){
      goodsLocation = LocationEntity();
      goodsLocation!.locationName = locationName!;
      goodsLocation!.id = locationId!;
    }
    loginEnabled = isCanSubmit();
  }
  
  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
          onWillPop: () {
        GetHelper.back();
        return Future.value(false);
      },
      child: GestureDetector(
      onTap: () => Get.back(),
        child: Container(
          padding: const EdgeInsets.only(bottom: 50),
          width: double.infinity,
          color: Colors.transparent,
          alignment: Alignment.center,
          height: double.infinity,
          child: Row(
            children: [
              SizedBox(width: 0.06.sw),
              Expanded(
                child: Container(
                  decoration: rs8,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        height: 95.w,
                        width: double.infinity,
                        child: Stack(
                          children: [
                            Container(
                                alignment: Alignment.center,
                                child: Text(MultiLanguage.locationEntry.tr,
                                    style: normalTextColor34)),
                            Positioned(
                              top: 10.w,
                              right: 0,
                              child: GestureDetector(
                                onTap: () => Get.back(),
                                child: Padding(
                                    padding: edgeAll24,
                                    child: LocalImage('common_close',
                                        package: Constant.packLib(), width: 26.w, height: 26.w)),
                              ),
                            )
                          ],
                        ),
                      ),
                      gapH24,
                      line1,
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          gapH24,
                          buildItem(
                              onTap: setGoodsLocation,
                              title: MultiLanguage.goodsLocation.tr,
                              hint: MultiLanguage.pleaseSelectAWarehouseLocation.tr,
                              content: goodsLocation !=null ? goodsLocation!.locationName:''),
                          gapH18,
                          buildItem(
                              onTap: difference,
                              title: MultiLanguage.causesOfDifferences.tr,
                              hint: MultiLanguage.pleaseSelectDifference.tr,
                              content: reason !=null ? reason!.label:''),
                          gapH24,
                        ],
                      ),
                      line1,
                      GradientButton(
                        ThemeUtil.getTheme(),
                        width: double.infinity,
                        height: 77.r,
                        margin: edgeV36H24 as EdgeInsets,
                        text: MultiLanguage.determine.tr,
                        onPressed: loginEnabled
                            ? determine
                            : null,
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(width: 0.06.sw),
            ],
          ),
        ),
      )),
    );
  }

  buildItem(
      {GestureTapCallback? onTap, required String title, required String hint, String? content}) {
    return Row(children: [
      Expanded(
          flex: 2, child: Text(title, style: normalTextColor28, textAlign: TextAlign.end)),
      Gaps.hGap24,
      Expanded(
          flex: 7,
          child: GestureDetector(
            onTap: onTap,
            child: Container(
                padding: edgeAll24,
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(30.0)),
                    border:
                    Border.all(color: ThemeUtil.getTheme().secondaryTextColor(), width: 1.0)),
                child: Row(children: [
                  Expanded(
                      child: Text(content == null || content.isEmpty ? hint : content,
                          style: content == null || content.isEmpty
                              ? TextStyles.textSecondary28
                              : normalTextColor28)),
                  LocalImage('common_grey_rightward_arrow',
                      package: Constant.packLib(), width: 20.w, height: 20.w),
                ])),
          )),
      gapW24,
    ]);
  }

  determine() {
    var map = {};

    List<dynamic> goodsDetails = [];
    for(int i = 0;i<list.length;i++){
      goodsDetails.add(
        {
          'goodsBarCode':list[i].goodsBarCode,
          'weight':list[i].stockInWeight,
        }
      );
    }
    map['id'] = id;
    map['detail'] = {
      'goodsCode': goodsCode,
      'stockInCount': stockInCount,
      'stockInWeight': stockInWeight,
      'locationId': goodsLocation!.id,
      'differenceReason': reason!=null ? reason!.value:null,
      'goodsDetails': goodsDetails,
    };
    FBHttpUtil.post<Map>(context, Apis.STOCK_IN_RECORDS,
        params: map,
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result))
        .then((value) {
      if (value['code'] == HttpConfig.successCode) {
        String? temporaryDifferenceReason;
        if(reason!=null){
          temporaryDifferenceReason = reason!.label;
        }
        updatePosition(position,list,goodsLocation!.id,goodsLocation!.locationName,temporaryDifferenceReason);
        GetHelper.back();
        GetHelper.back();
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  setGoodsLocation(){
    FBHttpUtil.get<Map>(context, Apis.GET_BY_WAREHOUSEID,
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result))
        .then((value) {
      if (value['code'] == HttpConfig.successCode) {
        List<LocationEntity> locationEntities = jsonConvert.convertList<LocationEntity>(value['data']);
        if(locationId!=null && goodsLocation == null){
          goodsLocation = locationEntities.firstWhere((element) => locationId == element.id);
        }
        Get.toNamed(Routers.LOCATION_PAGE,arguments: {'Buyer':locationEntities,'SelectedBuyer':goodsLocation,'callback':updateUi});
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  updateUi(LocationEntity locationEntity){
    goodsLocation = locationEntity;
    loginEnabled = isCanSubmit();
    setState(() {});
  }

  difference(){
    FBHttpUtil.get<Map>(context, Apis.LIST_ALL_SIMPLE,
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result))
    .then((value) {
      if (value['code'] == HttpConfig.successCode) {
        List<ReasonEntity> reasons = jsonConvert.convertList<ReasonEntity>(value['data']);
        var newReasons = reasons.where((element) => element.dictType == "scm_stock_in_difference_reason").toList();
        singlePicker(context, selectData: reason ?? newReasons[0], data: newReasons,
            showTitleBar: true,
            title: Text(MultiLanguage.pleaseSelectDifference.tr,style: normalTextColor34,textAlign: TextAlign.center,),
            onConfirm: (var data, int position) {
              reason = data;
              loginEnabled = isCanSubmit();
              setState(() {});
            });
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  ///判断是否自家的服务器标准的json格式,默认是有code和data即可
  bool isStandardJson(Map<dynamic, dynamic> data) {
    return data.containsKey('code') && data.containsKey('data') && data.containsKey('msg');
  }

  bool isCanSubmit(){
    return goodsLocation!=null;
  }

}
